package com.ssu.judea.travlog;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.ssu.judea.travlog.util.JSONParseHelper;
import com.ssu.judea.travlog.util.UrlImageConverter;
import com.ssu.judea.travlog.view.DetailResultPointItemizedOverlay;
import com.ssu.judea.travlog.view.MyOverLay;
import com.ssu.judea.travlog.vo.Result;
import com.ssu.judea.travlog.vo.ResultPost;

import android.content.Intent;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewDetailActivity extends TravlogActivity implements OnClickListener {
	private Bundle extras;
	private ArrayList<ResultPost> postList;
	private MapView mapView;
	
	private int MaxLatitude;
	private int MinLatitude;
	private int MaxLongitude;
	private int MinLongitude;
	private GeoPoint centerPoint;
	private int currentCursor = 0;
	private DetailResultPointItemizedOverlay itemizedOverlay;
	private Button btnFollow;
	private Button btnMention;
	private TextView screenName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewdetail);
		
		ImageView profile = (ImageView)findViewById(R.id.imageProfile);
		screenName = (TextView)findViewById(R.id.textScreenName);
		TextView location = (TextView)findViewById(R.id.textLocation);
		TextView regdate = (TextView)findViewById(R.id.textRegdate);
		TextView count = (TextView)findViewById(R.id.textCountPost);
		btnFollow = (Button)findViewById(R.id.buttonFollow);
		btnMention = (Button)findViewById(R.id.buttonMention);
		btnFollow.setOnClickListener(this);
		btnMention.setOnClickListener(this);
		
		mapView = (MapView)findViewById(R.id.mapviews);
		
		
		extras = getIntent().getExtras();
		GeoPoint curPoint = new GeoPoint(
				(int)(extras.getDouble("latitude",0)*1E6),
				(int)(extras.getDouble("longitude",0)*1E6));
		mapView.getController().setCenter(curPoint);
		mapView.getController().setZoom(mapView.getMaxZoomLevel()-1);
		mapView.setBuiltInZoomControls(true);
		
		Geocoder coder = new Geocoder(this, Locale.getDefault());
		String curFeatureName = "";
		try {
			if(coder.getFromLocation(extras.getDouble("latitude",0), extras.getDouble("longitude",0), 1).size()>0 
				&& coder.getFromLocation(extras.getDouble("latitude",0), extras.getDouble("longitude",0), 1).get(0).getMaxAddressLineIndex()>0)
			curFeatureName = "at " + coder.getFromLocation(extras.getDouble("latitude",0), extras.getDouble("longitude",0), 1).get(0).getAddressLine(0);
			else
				curFeatureName = "unavaliable get Location info";
		} catch (IOException e) {
			Log.e("changdoc",e.getMessage());
		}
		
		UrlImageConverter converter = new UrlImageConverter();
		profile.setImageDrawable(converter.urlToDrawable(extras.getString("imageurl")));
		screenName.setText(extras.getString("twitterid"));
		location.setText(curFeatureName);
		regdate.setText(extras.getString("regdate"));
		count.setText("("+extras.getInt("postcount",0)+")");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(extras.getString("twitterid").equals(getTravlogApp().currentUser.getTwitterid())){
			btnFollow.setVisibility(Button.INVISIBLE);
			btnMention.setVisibility(Button.INVISIBLE);
		}
		getTravlogApp().getUserPostByDate(this, extras.getInt("memberseq"), extras.getString("regdate") );
	}
	
	public void completeGetUserPostByDate(String result) {
		if(result==null || result.length()<1){
			
		}else{			
			try {
				postList = JSONParseHelper.parseToResultPostList(new JSONArray(result));
			} catch (JSONException e) {
				Log.v("changdoc", e.getMessage());
				postList = null;
			}
			
			if(postList!=null){
				setResultPostOverlay();
			}
		}
		
		
		
	}

	private void setResultPostOverlay() {
		// "http:"+getTravlogApp().getSERVER_URL()+ ResultPost.getAttachimageurl() 
		
		if(postList.size()==0 || postList == null){
			getTravlogApp().alert("Any post not exist");
			finish();
		} else {
			if(postList.size() == 1){
				centerPoint = new GeoPoint((int)(postList.get(0).getLatitude()*1E6), (int)(postList.get(0).getLongitude()*1E6));
				
				mapView.getController().setZoom(mapView.getMaxZoomLevel()-5);
				
				itemizedOverlay = new DetailResultPointItemizedOverlay(this
						.getResources().getDrawable(R.drawable.marker),postList);
				for(ResultPost cur : postList){
					UrlImageConverter converter = new UrlImageConverter();
					itemizedOverlay.addOverlay(new OverlayItem(new GeoPoint((int)(cur.getLatitude()*1E6), (int)(cur.getLongitude()*1E6)), "", ""), 
							converter.urlToDrawable(cur.getAttachthumbnailurl()));
				}
				
				mapView.getOverlays().add(itemizedOverlay);
				
				mapView.invalidate();
				
			} else {
				
				for(int i=0; i<postList.size()-1;i++){
					ResultPost curData =  postList.get(i);
					ResultPost nextData = postList.get(i+1);
					GeoPoint startPoint = new GeoPoint((int)(curData.getLatitude()*1E6), (int)(curData.getLongitude()*1E6));
					GeoPoint endPoint = new GeoPoint((int)(nextData.getLatitude()*1E6), (int)(nextData.getLongitude()*1E6));
					
					MaxLatitude = (int)(curData.getLatitude()*1E6);
					MinLatitude = (int)(curData.getLatitude()*1E6);
					MaxLongitude = (int)(curData.getLongitude()*1E6);
					MinLongitude = (int)(curData.getLongitude()*1E6);
					
					if(MaxLatitude < nextData.getLatitude()*1E6) MaxLatitude = (int)(nextData.getLatitude()*1E6);
					if(MinLatitude > nextData.getLatitude()*1E6) MinLatitude = (int)(nextData.getLatitude()*1E6);
					if(MaxLongitude < nextData.getLongitude()*1E6) MaxLongitude = (int)(nextData.getLongitude()*1E6);
					if(MinLongitude > nextData.getLongitude()*1E6) MinLongitude = (int)(nextData.getLongitude()*1E6);
					
					drawPath(startPoint, endPoint, mapView, i==postList.size()-2);
				}
				
				itemizedOverlay = new DetailResultPointItemizedOverlay(this
						.getResources().getDrawable(R.drawable.marker),postList);
				for(ResultPost cur : postList){
					UrlImageConverter converter = new UrlImageConverter();
					itemizedOverlay.addOverlay(new OverlayItem(new GeoPoint((int)(cur.getLatitude()*1E6), (int)(cur.getLongitude()*1E6)), "", ""), 
							converter.urlToDrawable(cur.getAttachthumbnailurl()));
				}
				
				mapView.getOverlays().add(itemizedOverlay);
				
				mapView.invalidate();
				
				mapView.getController().zoomToSpan(Math.abs(Math.abs(MaxLatitude)-Math.abs(MinLatitude))*2, Math.abs(Math.abs(MaxLongitude)-Math.abs(MinLongitude))*2);
				if(mapView.getZoomLevel()<8){
					mapView.getController().setZoom(mapView.getMaxZoomLevel()-8);
				}
				Log.v("changdoc","Is it OK???"+Math.abs(Math.abs(MaxLatitude)-Math.abs(MinLatitude))*2+"/"+Math.abs(Math.abs(MaxLongitude)-Math.abs(MinLongitude))*2);
				centerPoint = new GeoPoint((int)(MaxLatitude+MinLatitude)/2, (int)(MaxLongitude+MinLongitude)/2);
			}
		}
		mapView.setBuiltInZoomControls(true);
		mapView.getZoomButtonsController().setZoomInEnabled(true);
		if(centerPoint!=null)
			mapView.getController().setCenter(centerPoint);
	}

	private void drawPath(GeoPoint src, GeoPoint dest,
			MapView mapView, boolean isEndPoint) {
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");// from
		urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
		urlString.append(",");
		urlString
				.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
		urlString.append("&daddr=");// to
		urlString
				.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
		urlString.append(",");
		urlString.append(Double
				.toString((double) dest.getLongitudeE6() / 1.0E6));
		urlString.append("&ie=UTF8&0&om=0v&output=kml");
		//Log.d("xxx", "URL=" + urlString.toString());
		// get the kml (XML) doc. And parse it to get the coordinates(direction
		// route).

		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		boolean successGetRoute = false;
		try {
			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setConnectTimeout(500);
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();
			//Log.d("xxx", "urlConnection=" + urlConnection);

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());
			//Log.d("xxx", "doc=" + doc);
			
			if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
				successGetRoute = true;
				String path = doc.getElementsByTagName("GeometryCollection")
						.item(0).getFirstChild().getFirstChild()
						.getFirstChild().getNodeValue();
				//Log.d("xxx", "path=" + path);
				String[] pairs = path.split(" ");
				String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
														// lngLat[1]=latitude
														// lngLat[2]=height
				// src
				GeoPoint startGP = new GeoPoint((int) (Double
						.parseDouble(lngLat[1]) * 1E6), (int) (Double
						.parseDouble(lngLat[0]) * 1E6));
				
				//mapView.getOverlays().add(new MyOverLay(startGP, startGP, currentCursor==0?0:1, false));
				GeoPoint gp1;
				GeoPoint gp2 = startGP;
				for (int i = 1; i < pairs.length; i++) // the last one would be
														// crash
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					// watch out! For GeoPoint, first:latitude, second:longitude
					gp2 = new GeoPoint(
							(int) (Double.parseDouble(lngLat[1]) * 1E6),
							(int) (Double.parseDouble(lngLat[0]) * 1E6));
					mapView.getOverlays().add(
							new MyOverLay(gp1, gp2, 2, false));
					//Log.d("xxx", "pair:" + pairs[i]);
				}
				//mapView.getOverlays().add(new MyOverLay(dest, dest, 3, isEndPoint)); // use
																			// the
																			// default
																			// color
			}else{
				//getTravlogApp().alert("Cannot get route info from Google.");
			}
			urlConnection.disconnect();
		} catch (MalformedURLException e) {
			//e.printStackTrace();
			//getTravlogApp().alert("Cannot get route info from Google.");
		} catch (IOException e) {
			//e.printStackTrace();
			//getTravlogApp().alert("Cannot get route info from Google.");
		} catch (ParserConfigurationException e) {
			//e.printStackTrace();
			//getTravlogApp().alert("Cannot get route info from Google.");
		} catch (SAXException e) {
			//e.printSt	ackTrace();
			//
		} catch (IllegalArgumentException e){
			//
		} catch (IllegalStateException e){
			//Log.v("changdoc",e.getMessage());
		}
		currentCursor ++;
		if(!successGetRoute){
			getTravlogApp().alert("Cannot get route info from Google.",true);
		}
	}

	@Override
	public void onClick(View v) {
		if(v==btnFollow){
			getTravlogApp().doFollow(ViewDetailActivity.this,screenName.getText().toString());
		}else if(v==btnMention){
			Intent intent = new Intent(ViewDetailActivity.this, UserMentionActivity.class);
			intent.setAction(screenName.getText().toString());
			startActivity(intent);
		}
	}
	
	public void completeFollow(String resultStr){
		try {
			Result result = JSONParseHelper.parseToResult(new JSONObject(resultStr));
			getTravlogApp().alert(result.getMessage());
		} catch (JSONException e) {
			Log.v("changdoc", e.getMessage());
			getTravlogApp().alert("Error!!\n"+e.getMessage());
		}
	}
	
	

}
